import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { useStore, type StoreState } from '@/store'
import { parseEnvList, matchWhiteList } from '@/utils/env'

const allowNoLogin: string[] = parseEnvList('VITE_ALLOW_NO_LOGIN')

// 显式声明store类型，避免类型推断问题
interface ProtectedRouteProps {
  roles?: string[]
}

export default function ProtectedRoute({ roles }: ProtectedRouteProps) {
  const isLogin = useStore((s: StoreState) => s.isLogin)
  const role = useStore((s: StoreState) => s.role)
  const location = useLocation()
  // 白名单内无需登录
  if (!isLogin && !matchWhiteList(location.pathname, allowNoLogin)) {
    return <Navigate to="/login" replace />
  }
  if (roles && !roles.includes(role)) {
    return <div style={{ padding: 32, textAlign: 'center', color: 'red' }}>无权限访问</div>
  }
  return <Outlet />
} 